<template>
    <div class="page-wrap">
        <sys-set @success="sysSetChange" :defaultSystem="system" v-if="!$store.getters.userInfo.employeeDTO.isShowSideTree" />
        <a-divider class="full-divider-h" v-if="!$store.getters.userInfo.employeeDTO.isShowSideTree" />
        <flexbox justify="space-between" align="flex-start" class="table-toolbar-wrap">
            <filter-form :system="system" @search="handleSearch" style="flex: 1" />
            <flexbox>
                <a-button type="primary" :disabled="!list.length || loading" class="margin-r-16" @click="handleExport(1)">导出</a-button>
                <a-tooltip title="表格列配置">
                    <column-setting :columns="settingColumns" @setColumns="setColumns" />
                </a-tooltip>
            </flexbox>
        </flexbox>
        <custom-table
            autoResize
            rowKey="id"
            size="small"
            :loading="loading"
            :columns="tableColumns"
            :data-source="list"
            :pagination="paginationConfig"
            class="margin-t-16"
            @change="handleTableChange"
        >
            <template #systemName="{ record }">
                <div v-if="record.pmpProductDetailDTO">
                    <router-link :to="{ path: '/productAnalysis/productDetail', query: { id: record.requireSystem } }">
                        {{ record.pmpProductDetailDTO.systemName }}
                    </router-link>
                </div>
            </template>
            <template #requireName="{ record }">
                <a @click.stop="showDetail(record.id)" v-copyText="record.requireName">{{ record.requireName }}</a>
                <a-tag v-if="record.requireChange === 0" color="orange" class="margin-l-8">需求变更</a-tag>
            </template>
            <template #jiraId="{ record }">
                {{ record.jiraId ? 'JIRA' : '' }}
            </template>
            <template #pmpLabels="{ record }">
                <a-tag color="blue" style="max-width: 100%; margin-bottom: 2px" v-fitText v-for="item of record.pmpLabels" :key="item.id">
                    {{ item.name }}
                </a-tag>
            </template>
            <template #requireType="{ record }">
                <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
            </template>
            <template #level="{ record }">
                <h-level :level="record.level" v-if="record.level" />
            </template>
            <template #stage="{ record }"> {{ $filters.valToNameFilter('stage', record.stage) }} </template>
            <template #status="{ record }">
                <flexbox>
                    <h-status-badge :status="record.status" />
                </flexbox>
            </template>
            <template #expectTime="{ record }"> {{ $filters.dateFilter(record.expectTime) }} </template>
            <template #updateTime="{ record }"> {{ $filters.dateFilter(record.updateTime) }} </template>
            <template #createTime="{ record }"> {{ $filters.dateFilter(record.createTime) }} </template>
            <template #onlineTime="{ record }">{{ $filters.dateFilter(record.onlineTime) }}</template>
            <template #action="{ record }">
                <TableAction :record="record" @actionEvent="handleMenuEvent" />
            </template>
        </custom-table>
        <relative-change-table ref="relativeChangeTableRef" />
    </div>
</template>

<script lang="ts">
import FilterForm from './components/FilterForm.vue';
import { HLevel, HProductType, HStatusBadge, SysSet, CustomTable, ColumnSetting } from '@/components';
import RelativeChangeTable from '@/components/Content/RelativeChangeTable.vue';
import TableAction from './components/tableAction.vue';
import { useRouter, useRoute } from 'vue-router';
import { useSystemSet } from '@/components/SysSet/hooks/useSystemSet';
import { useMessage } from '@/hooks/common/useMessage';
import {
    useTableData,
    useTableLoading,
    usePagination,
    useTableColumns,
    useTableRowSelect,
    useTableFormSearch,
    useTableAction,
    useTableToolbar
} from '@/components/Table/hooks/index';
import { useMountedAndActivated } from '@/hooks/common/useMountedAndActivated';
import store from '@/store';
import { defineComponent, ref, unref, computed, provide, getCurrentInstance } from 'vue';

export default defineComponent({
    components: {
        FilterForm,
        HLevel,
        HProductType,
        HStatusBadge,
        SysSet,
        RelativeChangeTable,
        TableAction,
        CustomTable,
        ColumnSetting
    },
    setup() {
        const instance: any = getCurrentInstance();
        provide('myProductRequire', instance.proxy);
        const router = useRouter();
        const route = useRoute();
        const relativeChangeTableRef = ref();
        const { loading, setLoading } = useTableLoading();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const { columns: tableColumns, setColumns, settingColumns } = useTableColumns('productRequirements');
        const { list, searchQuery, getList, handleTableChange, setSearchQuery } = useTableData(
            setLoading,
            paginationConfig,
            setPaginationConfig,
            'productRequirements'
        );
        const { selectedRowKeys, selectedRows, onSelectChange } = useTableRowSelect();
        const { handleSearch } = useTableFormSearch(setPaginationConfig, setSearchQuery, getList);
        const { showDetail, handleDelete, showRequireChangeDetail, handleChangeRequire } = useTableAction(
            'productRequirements',
            getList,
            relativeChangeTableRef
        );
        const { exportAllFile } = useTableToolbar(searchQuery, paginationConfig);
        const { system, sysSetChange } = useSystemSet(setPaginationConfig, setSearchQuery, getList);

        // 过滤下表头显示数据
        const filterColumns = computed(() => {
            return tableColumns.value.filter((item: any) => item.dataIndex !== 'agentUser');
        });
        // 发起
        const handleStartProcess = () => {
            store.commit('proRequire/SET_CHECKEDLIST', unref(selectedRows));
            router.push({
                path: '/productRequire/startProcess'
            });
        };
        // 操作回调
        const handleMenuEvent = ({ type, record }) => {
            const { id, requireName } = record;
            switch (type) {
                case 'detail':
                    showDetail(id);
                    return;
                case 'showChange':
                    showRequireChangeDetail(id, 1);
                    return;
                case 'change':
                    handleChangeRequire(id);
                    return;
                case 'delete':
                    handleDelete(id, requireName);
                    return;
            }
        };
        setSearchQuery({
            // admin: store.getters.userInfo.roles.includes('admin') ? 1 : 0, // 判断角色是否含有admin
            admin: store.getters.userInfo.roles.some((item) => ['admin', '观察者', '领导', '产品管理委员会'].includes(item)) ? 1 : 0
        });
        useMountedAndActivated(getList, false);
        if (route.query.systemId) {
            const systemId: any = route.query.systemId || null;
            system.value = systemId;
        }

        const handleExport = (type: 0 | 1) => {
            // 检查是否有有效的筛选条件
            const hasFilters = Object.keys(unref(searchQuery)).some((key) => {
                const value = unref(searchQuery)[key];
                // 排除默认的 admin 字段
                if (key === 'admin') {
                    return false;
                }
                // 检查数组类型
                if (Array.isArray(value)) {
                    return value.length > 0;
                }
                // 检查其他类型的值
                return value !== undefined && value !== '' && value !== null;
            });

            if (!hasFilters) {
                const { createConfirm } = useMessage();
                createConfirm({
                    title: '导出提示',
                    iconType: 'warning',
                    content: '为了确保数据导出的准确性和效率，请先设置筛选条件（如需求类型、优先级、状态等）再进行导出操作。',
                    okText: '我知道了',
                    centered: true,
                    cancelButtonProps: { style: { display: 'none' } }
                });
                return;
            }
            exportAllFile(type);
        };

        return {
            relativeChangeTableRef,
            filterColumns,
            handleStartProcess,
            system,
            sysSetChange,
            handleMenuEvent,
            list,
            tableColumns,
            settingColumns,
            loading,
            selectedRowKeys,
            selectedRows,
            paginationConfig,
            handleTableChange,
            onSelectChange,
            showDetail,
            handleSearch,
            handleExport,
            setColumns
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    min-height: 100%;
    padding: 8px 24px 12px 24px;
    background: #fff;
    .table-toolbar-wrap {
        margin-bottom: 16px;
        .ant-btn + .ant-btn {
            margin-left: 8px;
        }
    }
    .table-title {
        font-size: 16px;
        font-weight: bold;
    }
}
</style>
